package com.imb.common.core.jwt;


import cn.hutool.jwt.JWTException;
import com.imb.common.core.enums.PrErrorEnum;
import com.imb.common.core.generationID.SnowFlake;
import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

/**
 * jwt工具类
 */
public class JwtUtil {

    //有效期为
    // 60 * 60 *1000  一个小时
    private static final Long JWT_TTL = 9999999 * 60 *1000L;
    //设置秘钥明文
    private static final String JWT_KEY = "sangeng";

    private static final SnowFlake SNK = new SnowFlake();

    private static String getUUID(){
        return String.valueOf(SNK.nextId()).replaceAll("-", "");
    }

    /**
     * 生成jtw
     * @param subject token中要存放的数据（json格式）
     * @return
     */
    public static String createJWT(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间
        return builder.compact();
    }

    /**
     * 生成jtw
     * @param subject token中要存放的数据（json格式）
     * @param ttlMillis token超时时间
     * @return
     */
    public static String createJWT(String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
        return builder.compact();
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttlMillis==null){
            ttlMillis=JwtUtil.JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)              //唯一的ID
                .setSubject(subject)   // 主题  可以是JSON数据
                .setIssuer("sg")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
                .setExpiration(expDate);

    }

    public static String refreshToken(String token) throws Exception {
        Claims claims = parseJWT(token);

        // 当前时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        // 设置新的过期时间
        Date newExpirationDate = new Date(nowMillis + JWT_TTL);
        // 重新创建 JWT
        return Jwts.builder()
                .setClaims(claims)
                .setIssuer("sg")
                .setIssuedAt(now)
                .setExpiration(newExpirationDate)
                .signWith(SignatureAlgorithm.HS256, generalKey())
                .compact();
    }

    public static void main(String[] args) throws Exception {
        // 创建一个 JWT
        String token = createJWT("John Doe");
        System.out.println("Initial Token: " + token);

        String token2="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMjg4OTAzMjM0OTY1OTk1NTIwIiwic3ViIjoiMTgzODA5ODAxNTMzNTEzNzI4MiIsImlzcyI6InNnIiwiaWF0IjoxNzI3MzQwMDc4LCJleHAiOjE3MjczNDM2Nzh9.Hef6JM_AogYzycViZ8Uk2aWokeV6j8kwLyt8k2qlRW8";
//        // 解析 JWT
//        Claims claims = parseJWT(token2);
//        System.out.println("Claims: " + claims);

        // 刷新 JWT
        String refreshToken = refreshToken(token);
        System.out.println("Refreshed Token: " + refreshToken);

        // 解析刷新后的 JWT
        Claims refreshedClaims = parseJWT(refreshToken);
        System.out.println("Refreshed Claims: " + refreshedClaims);


        System.out.println(venJwt(refreshToken));
    }

    /**
     * 创建token
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createJWT(String id, String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
        return builder.compact();
    }

//    public static void main(String[] args) throws Exception {
//        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//        String s=bCryptPasswordEncoder.encode("123456");
//        System.out.println(s);
////        System.out.println(bCryptPasswordEncoder.matches("123456",s));
////        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMDc4Njc5Mjg2ODc0ODk4NDMyIiwic3ViIjoiMTIzNDU2IiwiaXNzIjoic2ciLCJpYXQiOjE2NzcyMTg3ODIsImV4cCI6MTY3NzIyMjM4Mn0.sZAb5Z8fsRy_IFkR1kbKxb9SHFqXyzh_vZ7k3ETdafo";
////        Claims claims = parseJWT(token);
////        System.out.println(claims);
//        String token2=createJWT("123456");
//        System.out.println(token2);
//        String tk="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMDc4OTczMDMzMTkzOTMwNzUyIiwic3ViIjoidXNlcjIiLCJpc3MiOiJzZyIsImlhdCI6MTY3NzI4ODgxNywiZXhwIjoxNjc3MjkyNDE3fQ.x-NoifbdWn2dgkLg_i3TZqxIyg7qniXfVD1_Xu1_YI0";
//        System.out.println(bCryptPasswordEncoder.encode(token2));
//        //String g=bCryptPasswordEncoder.encode(tk);
//        System.out.println(parseJWT(token2));
//        System.out.println(parseJWT(tk));
//       // System.out.println(g);
//        //System.out.println(bCryptPasswordEncoder.matches(tk,g));
//
//    }

    /**
     * 生成加密后的秘钥 secretKey
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 解析
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static String parseJWTKey(String token){
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            //e.printStackTrace();
            throw new RuntimeException(PrErrorEnum.ERROR_1003.getInfo());
        }
        return userid;
    }

    public static boolean venJwt(String jwt){
        boolean p=true;
        try {
            parseJWT(jwt);
        }catch (ExpiredJwtException e){
            throw new JWTException(PrErrorEnum.ERROR_1007.getInfo());
        }catch (Exception e){
            e.printStackTrace();
            p=false;
        }
        return p;
    }

}
